
from flask import request

from . import api
from utils.decorators.check_sign import check_sign
from utils.session import session
from plugins_v3.experiment import config
from lxml import etree
from plugins_v3._login.login import experiment_login
from utils.decorators.request_limit import request_limit
from utils.decorators.cache import cache


@api.route('/experiment', methods=['GET'])
@check_sign(check_args={'name', 'passwd'})
@request_limit(5)
@cache({'name'}, 300)
def experiment():
    name = request.args.get('name', type=str)
    passwd = request.args.get('passwd', type=str)
    cookies = experiment_login(name, passwd)
    post_data = {
        'Referer': 'http://222.31.49.141/aexp/stuLeft.jsp'
    }
    experiment_list = []
    cur = 1
    page_sum = 2
    while True:
        if cur > page_sum:
            break
        rq = session.get(url=config.index_url+str(cur), headers=post_data, cookies=cookies).content.decode()
        # 将 HTML 字符串转换为 Element 对象
        tree = etree.HTML(rq)
        if cur == 1:
            page_sum = int(tree.xpath('normalize-space(//p/text())')[10])
        rows = tree.xpath('//*[@id="tab2"]/table/tbody/tr')
        # 遍历每个<tr>元素
        for row in rows:
            experiment_per = {}
            # 选择当前行下的所有<td>元素
            cells = row.xpath('.//td')
            # 遍历每个<td>元素并打印文本内容
            for index, table_cell in enumerate(cells):
                if index == 0:
                    experiment_per["coursename"] = table_cell.xpath('normalize-space(./strong/text())')
                elif index == 1:
                    experiment_per["experimentname"] = table_cell.text
                elif index == 2:
                    experiment_per["time"] = '第'+table_cell.text.strip()
                elif index == 3:
                    experiment_per["adress"] = table_cell.text
                elif index == 4:
                    experiment_per["teachername"] = table_cell.text
                    break
            if experiment_per != {}:
                experiment_list.append(experiment_per)
        cur += 1
    return {
        'code': 0,
        'data': experiment_list
    }



